package com.example.leetcode.c101_c200.c105;
/**
 * 根据一棵树的前序遍历与中序遍历构造二叉树。
 *
 * 注意:
 * 你可以假设树中没有重复的元素。
 *
 * 例如，给出
 *
 * 前序遍历 preorder = [3,9,20,15,7]
 * 中序遍历 inorder = [9,3,15,20,7]
 * 返回如下的二叉树：
 *
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */

import com.example.leetcode.common.TreeNode;
import com.example.leetcode.common.TreeNodeWrapper;

import java.util.Arrays;

/**
 * 从前序与中序遍历序列构造二叉树
 * @author zhanpengguo
 * @date 2020/10/2 10:43
 */
public class Solution {


    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length == 0) {
            return null;
        }
        if (preorder.length == 1) {
            return new TreeNode(preorder[0]);
        }
        int rootVal = preorder[0];
        TreeNode root = new TreeNode(rootVal);
        int index = -1;
        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == rootVal) {
                index = i;
            }
        }
        int[] inLeft = Arrays.copyOfRange(inorder, 0, index);
        int[] inRight = Arrays.copyOfRange(inorder, index + 1, inorder.length);
        int[] preLeft = Arrays.copyOfRange(preorder, 1, inLeft.length+1);
        int[] preRight = Arrays.copyOfRange(preorder, inLeft.length + 1, preorder.length);
        root.left = buildTree(preLeft, inLeft);
        root.right = buildTree(preRight, inRight);
        return root;
    }

    public static void main(String[] args) {
        int[] preorder = {3,9,8,20,6,15,7};
        int[] inorder =  {8,9,20,3,15,6,7};
//        TreeNode root = TreeNodeWrapper.stringToTreeNode("[3,9,6,8,20,15,7]");
//        String s1 = "[3,9,6,8,20,15,7]";
//        String s2 = "[8,9,20,3,15,6,7]";
//        TreeNodeWrapper.prettyPrintTree(root);
        Solution solution = new Solution();
        TreeNode treeNode = solution.buildTree(preorder, inorder);
        TreeNodeWrapper.prettyPrintTree(treeNode);
    }
}
